package com.jhhc.StormSurgeForecast.AstronomicalTide.Util;

import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.BDMS_FBC_RESULT_P;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.BDMS_ST_ASTROTD_F;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.ModelInfo.Lvl;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.ModelInfo.StationInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LYQ
 */
@Component
public class ModelFileRead {

    /**
     * 获取站点信息数据 读文件
     * @param path 文件路径，目录
     * @return stationInfos 站点信息集合
     */
    public static List<StationInfo> getStationInfos(String path){
        path = path + File.separator + "GWPstas.dat";
        System.out.println("文件路径：" + path);
        File file = new File(path);
        if (file.exists()) {
            try {
                String value;
                BufferedReader br = new BufferedReader(new FileReader(path));
                br.readLine();
                List<StationInfo> stationInfos = new ArrayList<>();
                StationInfo stationInfo = null;
                while ((value = br.readLine()) != null){
                    if (!"".equals(value)) {
                        stationInfo = new StationInfo();
                        String[] infos = value.split("\\s+");
                        stationInfo.setLon(infos[0].trim());
                        stationInfo.setLat(infos[1].trim());
                        stationInfo.setStationNm(infos[2].trim());
                        if (infos.length > 3) {
                            stationInfo.setStationCode(infos[3].trim());
                            stationInfo.setCity(infos[4].trim());
                        }
                        stationInfos.add(stationInfo);
                    }
                }
                br.close();
               return stationInfos;
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件读取异常");
                return null;
            }
        }else {
            System.out.println("文件不存在");
            return null;
        }
    }

    /**
     * 解析构造入库数据
     * 曙光超算模型文件
     * @param path 文件路径，目录
     * @return BDMS_FBC_RESULT_P 入库对象
     */
    public List<BDMS_FBC_RESULT_P> insertReadFors61(String path, String calSchemeId,int dttp) {
        List<StationInfo> stationInfos = ModelFileRead.getStationInfos(path);
        if (stationInfos != null) {
            path = path + File.separator  + "fort.61";
            System.out.println("文件路径：" + path);
            File file = new File(path);
            if (file.exists()) {
                try {
                    BufferedReader br = new BufferedReader(new FileReader(path));
                    String value;
                    br.readLine();
                    br.readLine();
                    List<BDMS_FBC_RESULT_P>  pList = new ArrayList<>();
                    BDMS_FBC_RESULT_P p = null;
                    for (StationInfo stationInfo : stationInfos) {
                        p = new BDMS_FBC_RESULT_P();
                        p.setCschemeid(calSchemeId);
                        p.setDttp(dttp);
                        if (stationInfo.getStationCode() != null) {
                            p.setPtkey(stationInfo.getStationCode());
                        }
                        p.setDtvalues("");
                        pList.add(p);
                    }
                    while ((value = br.readLine()) != null){
                        for (BDMS_FBC_RESULT_P bdmsFbcResultP : pList) {
                            value = br.readLine();
                            if (value != null) {
                                //System.out.println(value);
                                String[] strings = value.split("\\s+");
                                bdmsFbcResultP.setDtvalues(bdmsFbcResultP.getDtvalues() +
                                        ReadUtil.dataForm(strings[strings.length - 1].trim()));
                            }
                        }
                    }
                    //遍历bdms_fbc_result_pList，删除字段Ptkey==null的对象
                    pList.removeIf(bdmsFbcResultP -> bdmsFbcResultP.getPtkey() == null);
                    br.close();
                    return pList;
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("文件读取异常");
                    return null;
                }
            } else {
                System.out.println("文件不存在");
                return null;
            }
        }else {
            return null;
        }
    }

    /**
     * 读取lvl文件方法
     * @param multipartFile 文件
     */
    public Lvl read(MultipartFile multipartFile, int unitName){
        try {
            // 获取文件名
            String fileName = multipartFile.getOriginalFilename();
            // 获取文件后缀
            assert fileName != null;
            String prefix = fileName.substring(fileName.lastIndexOf("."));
            File file = File.createTempFile(fileName, prefix);
            multipartFile.transferTo(file);
            Lvl lvl = new Lvl();
            String str;
            TimeUtil timeUtil = new TimeUtil();
            FileInputStream fis = new FileInputStream(file);;
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            List<BDMS_ST_ASTROTD_F> astronomicalTides = new ArrayList<>();
            BDMS_ST_ASTROTD_F astronomicalTide = null;
            List<BDMS_ST_ASTROTD_F> eigenvalues = new ArrayList<>();
            List<String> stationCodes = new ArrayList<>();
            String min;
            while ((str = br.readLine()) != null){
                String[] values = str.split(",");
                min = String.format("%.2f",Double.parseDouble(values[4].trim()));
                String[] hm = min.split("\\.");
                astronomicalTide = new BDMS_ST_ASTROTD_F();
                if (!stationCodes.contains(values[0].trim())) {
                    stationCodes.add(values[0].trim());
                }
                if (values[4].trim().split("\\.").length > 1) {
                    astronomicalTide.setStcd(values[0].trim());
                    astronomicalTide.setYmdh(timeUtil.setTime(values[1].trim(),values[2].trim(),values[3].trim(),
                            hm[0].trim(),hm[1].trim()));
                    astronomicalTide.setFtdz(Double.parseDouble(String.format("%.2f",Double.parseDouble(values[5].trim()))));
                    astronomicalTide.setUnitname(unitName);
                    eigenvalues.add(astronomicalTide);
                }else {
                    astronomicalTide = new BDMS_ST_ASTROTD_F();
                    astronomicalTide.setStcd(values[0].trim());
                    astronomicalTide.setYmdh(timeUtil.setTime(values[1].trim(),values[2].trim(),values[3].trim(),
                            values[4].trim()));
                    astronomicalTide.setFtdz(Double.parseDouble(String.format("%.2f",Double.parseDouble(values[5].trim()))));
                    astronomicalTide.setHltdmk(0);
                    astronomicalTide.setUnitname(unitName);
                    astronomicalTides.add(astronomicalTide);
                }
                System.out.println(astronomicalTide.toString());
            }
            fis.close();
            isr.close();
            br.close();
            lvl.setEigenvalue(eigenvalues);
            lvl.setAstronomicalTide(astronomicalTides);
            lvl.setStationCodes(stationCodes);
            return lvl;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取文件错误");
            return null;
        }
    }
    /**
     * 判断高低潮
     * @param eigenvalues 一天的高低潮参数
     * @return eigenvalues
     */
    public List<BDMS_ST_ASTROTD_F> estimate(List<BDMS_ST_ASTROTD_F> eigenvalues){
        if (eigenvalues.size() == 1) {
            eigenvalues.get(0).setHltdmk(1);
        }else {
            double f1 = -10;
            double f2 = -10;
            double f3 = -10;
            double f4 = -10;
            switch (eigenvalues.size()) {
                case 4:
                    f1 = eigenvalues.get(0).getFtdz();
                    f2 = eigenvalues.get(1).getFtdz();
                    f3 = eigenvalues.get(2).getFtdz();
                    f4 = eigenvalues.get(3).getFtdz();
                    break;
                case 3:
                    f1 = eigenvalues.get(0).getFtdz();
                    f2 = eigenvalues.get(1).getFtdz();
                    f3 = eigenvalues.get(2).getFtdz();
                    break;
                case 2:
                    f1 = eigenvalues.get(0).getFtdz();
                    f2 = eigenvalues.get(1).getFtdz();
                    break;
                case 1:
                    f1 = eigenvalues.get(0).getFtdz();
                    break;
                default:
                    break;
            }
            if (f1 < f2) {
                //f1 低潮 f2 高潮
                if (f3 == -10) {
                    eigenvalues.get(0).setHltdmk(3);
                } else if (f1 < f3) {
                    eigenvalues.get(0).setHltdmk(4);
                    eigenvalues.get(2).setHltdmk(3);
                } else {
                    eigenvalues.get(0).setHltdmk(3);
                    eigenvalues.get(2).setHltdmk(4);
                }
                if (f4 == -10) {
                    eigenvalues.get(1).setHltdmk(1);
                } else if (f2 < f4) {
                    eigenvalues.get(1).setHltdmk(2);
                    eigenvalues.get(3).setHltdmk(1);
                } else {
                    eigenvalues.get(1).setHltdmk(1);
                    eigenvalues.get(3).setHltdmk(2);
                }
            } else {
                //f2 低潮 f1 高潮
                if (f3 == -10) {
                    eigenvalues.get(0).setHltdmk(1);
                } else if (f1 < f3) {
                    eigenvalues.get(0).setHltdmk(2);
                    eigenvalues.get(2).setHltdmk(1);
                } else {
                    eigenvalues.get(0).setHltdmk(1);
                    eigenvalues.get(2).setHltdmk(2);
                }
                if (f4 == -10) {
                    eigenvalues.get(1).setHltdmk(3);
                } else if (f2 < f4) {
                    eigenvalues.get(1).setHltdmk(3);
                    eigenvalues.get(3).setHltdmk(4);
                } else {
                    eigenvalues.get(1).setHltdmk(4);
                    eigenvalues.get(3).setHltdmk(3);
                }
            }
        }
        return eigenvalues;
    }

    /**
     * 读取天文潮矫正模型文件
     * @param path 文件路径
     * @param calSchemeId 计算方案id
     * @param dttp 数据类型
     */
    public List<BDMS_FBC_RESULT_P> modelJiaoZheng(String path,String calSchemeId,int dttp){
        File file = new File(path);
        if (file.exists()) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String value;
                String stationCode = "";
                List<BDMS_FBC_RESULT_P> pList = new ArrayList<>();
                BDMS_FBC_RESULT_P p = null;
                while ((value = br.readLine()) != null){
                    String[] dates = value.split("\\s");
                    if (!dates[0].trim().equals(stationCode)) {
                        if (p != null) {
                            if ("1919".equals(p.getPtkey())) {
                                p.setPtkey("70301400");
                            }
                            if ("1110".equals(p.getPtkey())) {
                                p.setPtkey("70703400");
                            }
                            pList.add(p);
                        }
                        stationCode = dates[0].trim();
                        p = new BDMS_FBC_RESULT_P();
                        p.setCschemeid(calSchemeId);
                        p.setDttp(dttp);
                        p.setPtkey(stationCode);
                        p.setDtvalues(ReadUtil.dataForm(dates[5].trim()));
                    }else {
                        if (p != null) {
                            p.setDtvalues(p.getDtvalues() + ReadUtil.dataForm(dates[5].trim()));
                        }
                    }
                }
                if (p != null) {
                    if ("1919".equals(p.getPtkey())) {
                        p.setPtkey("70301400");
                    }
                    if ("1110".equals(p.getPtkey())) {
                        p.setPtkey("70703400");
                    }
                    pList.add(p);
                }
                br.close();
                return pList;
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件读取异常");
                return null;
            }
        }else{
            System.out.println("找不到文件：" + path);
            return null;
        }
    }

    /**
     * 解析构造入库数据
     * 东中国海模型文件
     * @param path 文件路径
     * @param calSchemeId 计算方案id
     */
    public List<BDMS_FBC_RESULT_P> readtfupresuls(String path, String calSchemeId, int dttp) {
        List<StationInfo> stationInfos = ModelFileRead.getStationInfos(path);
        if (stationInfos != null) {
            path = path + File.separator + "tfupresuls.dat";
            System.out.println("文件路径：" + path);
            File file = new File(path);
            if (file.exists()) {
                try {
                    String value;
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    for (int i = 0; i < 8; i++) {
                        br.readLine();
                    }
                    List<BDMS_FBC_RESULT_P>  pList = new ArrayList<>();
                    BDMS_FBC_RESULT_P p = null;
                    for (StationInfo stationInfo : stationInfos) {
                        p = new BDMS_FBC_RESULT_P();
                        p.setCschemeid(calSchemeId);
                        p.setDttp(dttp);
                        p.setPtkey(stationInfo.getStationCode());
                        p.setDtvalues("");
                        pList.add(p);
                    }
                    String data;
                    while ((value = br.readLine()) != null){
                        String[] values = value.split(",");
                        if (values.length == pList.size() + 4) {
                            for (int j = 4; j < values.length; j++) {
                                if (j == values.length - 1) {
                                    values = values[j].trim().split("\\s+");
                                    data = values[0].trim();
                                    if ("NaN".equals(data)) {
                                        data = "0.00";
                                    }
                                    pList.get(j - 4).setDtvalues(pList.get(j - 4).getDtvalues() +
                                            ReadUtil.dataForm(data));
                                }else {
                                    data = values[j].trim();
                                    if ("NaN".equals(data)) {
                                        data = "0.00";
                                    }
                                    pList.get(j - 4).setDtvalues(pList.get(j - 4).getDtvalues() +
                                            ReadUtil.dataForm(data));
                                }
                            }
                        }else {
                            for (int j = 4; j < values.length - 1; j++) {
                                data = values[j].trim();
                                if ("NaN".equals(data)) {
                                    data = "0.00";
                                }
                                pList.get(j - 4).setDtvalues(pList.get(j - 4).getDtvalues() +
                                        ReadUtil.dataForm(data));
                            }
                        }
                    }
                    br.close();
                    pList.removeIf(bdmsFbcResultP -> bdmsFbcResultP.getPtkey() == null);
                    return pList;
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("文件读取异常");
                    return null;
                }
            }else {
                System.out.println("找不到文件：" + path);
                return null;
            }
        }else {
            return null;
        }
    }







}
